package com.surfilter.gsxt.crawler;

import org.openqa.selenium.phantomjs.PhantomJSDriver;
import com.surfilter.gsxt.util.HttpUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class PhantomJSDriverManager implements Comparable<PhantomJSDriverManager>{

	private String sessionId;
	
	private PhantomJSDriver driver;
	
	private boolean use;
	
	private Long useTime;
	
	private List<Long> scores = new ArrayList<Long>();
	
	protected PhantomJSDriverManager() {
		super();
	}
	
	protected void reopenDriver(){
		closeDriver();
		driver = HttpUtil.getPhantomJSDriver();
		sessionId = driver.getSessionId().toString();
		use = false;
		scores.clear();
	}
	
	protected void closeDriver(){
		try{
			if(driver != null){
				driver.close();
				driver.quit();
				driver = null;
			}			
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	protected PhantomJSDriverManager(String sessionId, PhantomJSDriver driver, boolean use, Long useTime) {
		super();
		this.sessionId = sessionId;
		this.driver = driver;
		this.use = use;
		this.useTime = useTime;
	}
	
	public String getSessionId() {
		return sessionId;
	}

	public void setSessionId(String sessionId) {
		this.sessionId = sessionId;
	}

	public PhantomJSDriver getDriver() {
		return driver;
	}

	public void setDriver(PhantomJSDriver driver) {
		this.driver = driver;
	}

	public boolean isUse() {
		return use;
	}

	public void setUse(boolean use) {
		this.use = use;
	}

	public Long getUseTime() {
		return useTime;
	}

	public void setUseTime(Long useTime) {
		this.useTime = useTime;
	}
	
	public void score_add(Long score){
		scores.add(score);
	}
	
	public void score(){
		scores.add(System.currentTimeMillis() - useTime);
	}
	
	public int sum_score(){
		int result = 0;
		if(scores.size() != 0){
			for(Long score : scores){
				result += score;
			}
			result = result/scores.size();			
		}
		return result;
	}
	
	public static void main(String[] args) {
		
		PhantomJSDriverManager manager1 = new PhantomJSDriverManager();
//		manager1.score_add(1000l);
		
		PhantomJSDriverManager manager2 = new PhantomJSDriverManager();
//		manager2.score_add(2000l);
		
		PhantomJSDriverManager manager3 = new PhantomJSDriverManager();
//		manager3.score_add(3000l);
		
		List<PhantomJSDriverManager> rts = new ArrayList<PhantomJSDriverManager>();
		rts.add(manager1);
		rts.add(manager2);
		rts.add(manager3);
		
		Collections.sort(rts);
		System.out.println(rts.get(0).sum_score());
//		PhantomJSDriver driver = HttpUtil.getPhantomJSDriver();
//		System.out.println(driver.getSessionId());
//		driver.close();
//		driver.quit();
	}

	public int compareTo(PhantomJSDriverManager o) {
		// TODO Auto-generated method stub
		if(o.sum_score() > this.sum_score()){
			return -1;
		}else if(o.sum_score() < this.sum_score()){
			return 1;
		}
		return 0;
	}
}
